package com.sgroup.studycountry.support.page;

import com.sgroup.studycountry.support.enums.OrderType;
import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.Arrays;

/**
 * 分页输入
 *
 * @author umi
 * @date 2021/9/25 17:18
 */
@Data
public class PageInput {

    /**
     * 页中元素数量
     */
    private int size;

    /**
     * 页号
     */
    private int page;

    /**
     * 排序规则
     */
    private OrderInput[] orders;

    /**
     * 转为Pageable对象
     *
     * @return Pageable对象
     */
    public Pageable toPageable() {
        Sort.Order[] orderList = Arrays.stream(orders).map((order) -> {
            if (order.getType() == OrderType.ASC) {
                return Sort.Order.asc(order.getField());
            }
            return Sort.Order.desc(order.getField());
        }).toArray(Sort.Order[]::new);
        return PageRequest.of(page, size, Sort.by(orderList));
    }
}
